<template>
  <div>
    <base-modal
      class="fault-modal"
      :title="title"
      :show.sync="visible"
      width="800px"
      @cancel="close">

      <div class="fault-modal-content">
        <!-- 搜索栏 -->
        <FaultLibraryHeader ref="FaultLibraryHeader" class="fault-library-header" @getData="getData" :task="task">
          <div slot="left"></div>
        </FaultLibraryHeader>

        <!-- 树 -->
        <div class="fault-modal-content-tree">
          <div class="title-tip">{{ $t('common.base.description1') }}</div>
          <tree-list 
            v-if="isRegister"
            :init-data="initData"
            ref="treeList" 
            :fault-list="faultList"
            :is-form-dialog="true"
            :is-register="isRegister"
            @check="handelCheckChange"
            @getData="$refs.FaultLibraryHeader && $refs.FaultLibraryHeader.getData()"/>

          <el-tree 
            v-else
            :class="checkBoxFlag ? 'checkTreeClass' : 'treeClass'"
            ref="tree" 
            :data="faultList" 
            :check-strictly="true" 
            :default-checked-keys="checkedKeys" 
            :props="defaultProps" 
            default-expand-all
            show-checkbox 
            node-key="id" 
            @check="handelCheckChange"
          >
            <div class="custom-tree-node" slot-scope="{ node, data }">
              <div class="title">
                <span class="icon" v-if="data.faultLabel">{{ data.faultLabel }}</span>
                {{ data.faultDesc }}
              </div>
            </div>
          </el-tree>
        </div>
      </div>

      <div slot="footer" class="dialog-footer" v-if="!this.isSelectParent">
        <el-button :disabled="pending" @click="close">{{ $t('common.base.cancel') }}</el-button>
        <el-button type="primary" :disabled="pending" @click="submit">{{ $t('common.base.submit') }}</el-button>
      </div>
    </base-modal>
  </div>
</template>
  
<script>
// util
import { t } from '@src/locales';
import { findParents } from '@src/modules/faultLibrary/utils/index';
import { isNumber } from '@src/util/type'
// api
import { librarySelect } from '@src/api/Fault';
// components
import FaultLibraryHeader from '@src/modules/faultLibrary/components/FaultLibraryHeader.vue';
import TreeList from '@src/modules/faultLibrary/components/TreeList.vue';

export default {
  name: 'ChooseFaultDialog',
  props: {
    editItem: {
      type: Object,
      default: () => ({})
    },
    defaultCheckedKeys: {
      type: Array,
      default: () => ([])
    },
    form: {
      type: String,
      default: ''
    },
    initData: {
      type: Object,
      default: () => ({})
    },
    task: {
      type: Object,
      default: () => ({})
    },
  },
  components: {
    FaultLibraryHeader,
    TreeList,
  },
  data() {
    return {
      pending: false,
      visible: false,
      defaultProps: {
        children: 'childrenList',
        label: 'faultDesc',
        disabled: 'disabled'
      },
      // 故障对象弹框展示
      faultObjDialogVisible: false,
      faultList: [],
      isSelectParent: false, // 是否在选上级
      fetchParams: {}, // 保留查询数据
      checkedKeys: [], // 当前选中的节点
      checkBoxFlag: true, // 是否只能选子节点
      treeListDialogInfo: []
    }
  },
  computed: {
    isEdit() {
      return this.editItem.id || false;
    },
    title() {
      return t('common.faultLibrary.tip2');
    },
    isRegister() {
      return this.form === 'register';
    }
  },
  methods: {
    /**
        * @description 打开添加备件弹窗
        */
    open(info) {
      this.pending = false;
      this.visible = true;

      // 需要默认勾选再打开，打开后之前添加的会被勾选，获取时获取的是之前的+现在选的
      if(this.defaultCheckedKeys?.length) {
        this.checkedKeys = this.defaultCheckedKeys;
        this.getData(this.fetchParams);
      }

      if(info) {
        this.treeListDialogInfo = [];
        this.$refs.treeList.setDialogInfo({
          isSelectParent: info.isSelectParent,
          checkedKeys: this.treeListDialogInfo,
          defaultCheckedKeys: this.defaultCheckedKeys,
          isDialog: true,
        });
        this.isSelectParent = info.isSelectParent;
        this.checkedKeys = info.defaultCheckedKeys;
        this.getData(this.fetchParams);
      }
      if(this.isRegister){
        this.$refs.treeList.setAllExpand(true)
        this.$refs.treeList.findExpandedNode()
      }
      this.$refs.FaultLibraryHeader.open()
    },
    /**
        * @description 关闭添加备件弹窗
        */
    close() {
      this.visible = false;
      this.fetchParams = {};
      this.$refs.FaultLibraryHeader?.clearSearchValue();
    },
    /**
        * @description 提交
        */
    submit() {
      const nodeList = this.$refs.tree.getCheckedNodes();
      this.$emit('submit', nodeList, this.faultList);
      this.$refs.tree.setCheckedKeys([]);
    },
    // 获取数列表
    async getData(params) {
      try {
        this.fetchParams = params;
        const res = await librarySelect(params);

        if (res.status === 0) {
          this.switchDataList(res.data || [])
          this.faultList = res.data || []
        }
      } catch (e) {
        console.log('librarySelect:', e)
      }
    },
    switchDataList(data) {
      // 将解决方案solutionList改为childrenList，且把解决方案的元素添加faultDesc字段值为solutionDesc字段
      data.map(item => {
        const { solutionList, childrenList } = item

        // 已选的内容置灰
        if(this.defaultCheckedKeys.includes(item.id)){
          item.disabled = true;
        }
                

        if (solutionList?.length && !this.isSelectParent) {
          solutionList.map(content => {
            content.faultDesc = content.solutionDesc
            content.faultLabel = this.$t('faultLibrary.solution')
          })

          item.childrenList = item.childrenList ? [...item.childrenList, ...solutionList] : [...solutionList]
        }

        // 是否可选
        let childrenList_ = []
        item?.childrenList?.forEach((v, i)=> {
          // 工单详情-故障清单，新建故障描述选择上级故障描述时，不能选择已有解决方法的故障描述；
          if(this.isSelectParent && v.solutionList?.length) {
            return;
          }

          if(this.defaultCheckedKeys.includes(v.id)){
            v.disabled = true;
          }
          childrenList_.push(v)
        });
        item.childrenList = childrenList_
                

        if (childrenList?.length) {
          this.switchDataList(item.childrenList)
        }
      })
    },
    // 添加
    addFaultHandle() {

    },
    // 单选上级
    handelCheckChange(data) {
      if(!this.isSelectParent) return;
            
      const parents = findParents(this.faultList, data.id);
      data.parentDescAll = parents.map(x => x.faultDesc).join('/');
      this.$emit('click', data);

      if(!this.isRegister) {
        this.$refs.tree.setCheckedKeys([]);
      }else {
        this.treeListDialogInfo = [data.id];
        this.$refs.treeList.setCheckedKeys();
      }
      this.visible = false;
    }
  },
}
</script>
  
<style lang="scss" scoped>
.fault-modal {
    ::v-deep .base-modal-body {
        padding: 16px !important;
    }

    &-content {
        &-search {
            height: 32px;
            padding: 16px 0;
            background-color: skyblue;
            margin-bottom: 16px;
        }

        &-tree {
          min-height: 400px;
            .title-tip {
                padding: 9px 48px;
                background: #F5F8FA;
                color: #595959;
                font-size: 14px;
                border-bottom: 1px solid $color-border-l2;
            }
            section {
              overflow: inherit;
            }
        }

        ::v-deep .content-right {
            >div {
                flex: 1
            }
        }
    }

    .btn-group {
        text-align: center;
        margin-top: 16px;

        .el-button {
            width: 72px !important;
            border-radius: $button-radius-base;
        }
    }
}

::v-deep .el-tree-node__content {
    border-bottom: 1px solid #EBEEF5;
    padding: 9px 0;
    height: 40px;

    .custom-tree-node.select,
    &:hover {
        .btn-parent {
            display: flex;
        }
    }
}

.custom-tree-node {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    padding-right: 24px;

    .title {
        color: #262626;

        .icon {
            background: #F4F4F5;
            border: 1px solid #E9E9EB;
            line-height: 20px;
            border-radius: 2px;
            padding: 0px 8px;
            margin-right: 8px;
            color: #909399;
            font-size: 12px;
        }
    }
}
::v-deep .el-checkbox {
    width: auto !important;
    margin-right: 20px;
}

::v-deep {
    .checkTreeClass {
      padding-top: 15px;
      padding-left: 10px;
       // 不可全选样式
    }
}
</style>